import React, { Component } from 'react'
import { Carousel, Image } from 'react-bootstrap'
import { httpGet } from '../../../../services/http'
import { withRouter } from 'react-router-dom'
import Loading from '../../../../components/Loading/Loading'
import intl from 'react-intl-universal'
import './HomeCarousel.less'

class HomeCarousel extends Component {
  state = { carouselList: [], flag: false }

  async componentDidMount () {
    const [res, err] = await httpGet({ url: '/carousel/getCarousel' })
    if (res) {
      const { data } = res
      this.setState({
        carouselList: data
      })
      this.setIntl()
    } else {
      console.log(err)
    }
  }

  setIntl = () => {
    const { carouselList } = this.state
    let zh = {}
    let en = {}
    for (let i of carouselList) {
      zh[i.enTitle] = i.zhTitle
      en[i.enTitle] = i.enTitle
    }
    intl.load({
      'zh-CN': zh,
      'en-US': en
    })
    this.setState({
      flag: true
    })
  }

  handleClick = (gid) => {
    const { history } = this.props
    history.push('/goodsDetail/' + gid)
  }

  render () {
    const { carouselList } = this.state
    return (
      this.state.flag ? <Carousel id = {'home-carousel'}>
        {
          carouselList.map(ele => {
            return <Carousel.Item onClick = {() => {this.handleClick(ele.gid)}}
                                  interval = {3000}
                                  key = {ele._id}>
              <Image fluid
                     src = {ele.img}
                     roundedCircle />
              <Carousel.Caption as = {'h3'}>
                {intl.get(ele.enTitle)}
              </Carousel.Caption>
            </Carousel.Item>
          })
        }
      </Carousel> : <Loading />
    )
  }
}

export default withRouter(HomeCarousel)
